<template>
  <div style="padding: 20px">

    <!-- 预约记录ID查询 -->
    <div style="display: inline-block" >
      <el-input style="width:160px" icon="search" 
      v-model="inputQueryField" 
      placeholder="请输入用户姓名"
      @keyup.enter="queryByKeywords"></el-input>
      <el-button
        type="primary"
        style="margin-left: 5px"
        @click="queryByKeywords">查询
      </el-button>
      &ensp;
      <el-button type="primary" icon="el-icon-plus" @click="addUser"
        >添加用户</el-button>
      <br />
    </div>
  
    <!-- 用户列表展示 -->
    <el-table
      :data="userList"
      height="450"
      style="width: 100%"

      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
      @cell-dblclick="tableEdit"
    >
      <el-table-column prop="id" width="90" label="ID" sortable>
      </el-table-column>
      <el-table-column
        prop="userId"
        label="用户账号"
        width="150"
        sortable
      ></el-table-column>
      <el-table-column
        prop="userName"
        label="用户姓名"
        width="150"
        sortable
      ></el-table-column>
      <el-table-column
        prop="userPassword"
        label="用户密码"
        width="120"
        sortable
      ></el-table-column>
      <el-table-column
        prop="userFlag"
        label="用户权限"
        width="120"
        sortable
      ></el-table-column>
      <el-table-column
        prop="userObject"
        label="所属学院"
        width="120"
        sortable
      ></el-table-column>
      <el-table-column
        prop="userGrade"
        label="所属年级"
        width="120"
        sortable
      ></el-table-column>
      <el-table-column
        prop="userClass"
        label="所属班级"
        width="120"
        sortable
      ></el-table-column>
      <el-table-column
        prop="userPhone"
        label="联系电话"
        width="120"
        sortable
      ></el-table-column>
      <el-table-column
        prop="userSchool"
        label="所在校区"
        width="150"
        sortable
      ></el-table-column>
      <el-table-column
        prop="userAddress"
        label="办公地址"
        width="150"
        sortable
      ></el-table-column>
      <el-table-column label="是否冻结" width="180" sortable>
        <template #default="scope">
          <el-switch
            active-color="grey"
            active-text="冻结"
            :active-value="1"
            inactive-color="#13ce66"
            inactive-text="正常"
            :inactive-value="0"
            v-model="scope.row.userFreeze"
            @change="changeFreeze(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        :formatter="dateFormat"
        width="150"
        sortable
      ></el-table-column>
      <el-table-column
        prop="lastUpdateTime"
        label="上次更新时间"
        :formatter="dateFormat"
        width="150"
        sortable
      ></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  
    <!-- dialog弹出框，添加用户 -->
    <el-dialog title="添加用户" v-model="adduserdialogVis" width="40%">
      <el-form
        style="padding: 5px"
        :model="adduserform"
        ref="adduserform"
        :rules="rules"
      >
        <el-form-item label="用户账号" prop="userId">
          <el-input v-model="adduserform.userId" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName">
          <el-input
            v-model="adduserform.userName"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="userPassword">
          <el-input
            v-model="adduserform.userPassword"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户权限" prop="userFlag">
          <el-select
            v-model="adduserform.userFlag"
            style="width: 200px"
            placeholder="请选择角色"
          >
            <el-option
              v-if="user.userFlag === 1"
              label="学院管理员"
              value="2"
            ></el-option>
            <el-option
              v-if="user.userFlag === 2"
              label="院领导"
              value="3"
            ></el-option>
            <el-option
              v-if="user.userFlag === 2"
              label="辅导员"
              value="4"
            ></el-option>
            <el-option
              v-if="user.userFlag === 2"
              label="班主任"
              value="5"
            ></el-option>
            <el-option
              v-if="user.userFlag === 1"
              label="咨询师"
              value="7"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="adduserform.userFlag === '7'"
          label="所属校区"
          prop="userSchool"
        >
          <el-input
            v-model="adduserform.userSchool"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="adduserform.userFlag !== '7'"
          label="所属学院"
          prop="userObject"
        >
          <el-input
            v-model="adduserform.userObject"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="adduserform.userFlag === '4'|| adduserform.userFlag === '5'"
          label="所属年级"
          prop="userGrade"
        >
          <el-input
            v-model="adduserform.userGrade"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="adduserform.userFlag === '5'"
          label="所属班级"
          prop="userClass"
        >
          <el-input
            v-model="adduserform.userClass"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="userPhone">
          <el-input
            v-model="adduserform.userPhone"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item label="办公地址" prop="userAddress">
          <el-input
            v-model="adduserform.userAddress"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item style="padding-left: 80px">
          <el-button type="primary" @click="onsubmitUser()">添加</el-button>
          <el-button @click="resetUser('adduserform')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
 </div>
</template>

<script>
import axios from "axios";
import { baseUrl } from "@/utils/request";
import moment from "moment";

export default {
  data() {
    return {
      inputQueryField:"",
      user: {},
      userList: [],
      adduserdialogVis: false,
      adduserform: {
        // 添加用户
        userId: "",
        userName: "",
        userPassword: "",
        userFlag: "",
        userPhone: "",
        userSchool: "",
        userGrade: "",
        userObject: "",
        userClass: "",
        userAddress: "",
      },
      rules: {
        userId: [
          { required: true, message: "请填入用户工号", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "请填入用户姓名", trigger: "blur" },
        ],
        userPassword: [
          { required: true, message: "请填入用户密码", trigger: "blur" },
        ],
        userPhone: [
          { min: 11, max: 11, message: "手机号长度为11位", trigger: "blur" },
        ],
        userSchool: [
          { required: true, message: "请填入用户所在校区", trigger: "blur" },
        ],
        userObject: [
          { required: true, message: "请填入用户所在学院", trigger: "blur" },
        ],
        userGrade: [
          { required: true, message: "请填入用户所在年纪", trigger: "blur" },
        ],
        userClass: [
          { required: true, message: "请填入用户所在班级", trigger: "blur" },
        ],
        // userAddress: [
        //   { required: true, message: "请填入用户办公地址", trigger: "blur" },
        // ],
      },
    };
  },
  created() {
    let userStr = sessionStorage.getItem("user") || "{}";
    this.user = JSON.parse(userStr);
    this.adduserform.userObject = this.user.userObject;
    this.getUserList();
  },
  methods: {
    queryByKeywords(){
      // 根据用户名搜索
      var search = this.inputQueryField;
      let keyList = [];
      this.userList.forEach((item) => {
        if(search == item.userName){
          console.log(item);
          keyList.push(item);
          console.log(keyList)
        }
      })
      this.userList = [];
      this.userList = keyList;
      console.log(this.userList);
      // this.getUserList();
    },
    changeFreeze(row) {
      // 修改用户账号的冻结情况
      axios
        .post(baseUrl + "/userlogin/updatafreeze/", {
          userId: row.userId,
          userFreeze: row.userFreeze,
        })
        .then((res) => {
          let freeflag = row.userFreeze;
          if (freeflag == "1") {
            this.$message({
              type: "success",
              message: "该用户已冻结!",
            });
          } else {
            this.$message({
              type: "success",
              message: "该用户已取消冻结!",
            });
          }
        });
    },
    getUserList() {
      // 获取用户列表
      axios.get(baseUrl + "/userlogin/list/").then((res) => {
        console.log("原始", res);
        if (res.status == "200") {
          // 当userFlag=2的院管时，要对userFlag=1的用户进行过滤（不展示）
          // 不同学院的院管，无法看到其他院管信息，即userFlag=2的只能看到他们学院的3，4，5的老师
          if (this.user.userFlag === 2) {
            let tmp = [];
            this.userList = [];
            tmp = res.data;
            tmp.forEach((item) => {
              if (item.userFlag != 1 && item.userFlag != 2 && item.userFlag != 7 && item.userObject == this.user.userObject) {
                this.userList.push(item);
              }
            });
          }else{
            let tmp = [];
            this.userList = [];
            tmp = res.data;
            tmp.forEach((item) => {
              if (item.userFlag != 3 && item.userFlag != 4 && item.userFlag != 5 && item.userFlag != 1) {
                this.userList.push(item);
              }
            });
            // this.userList = res.data;
          }
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    addUser() {
      this.adduserdialogVis = true;
    },
    onsubmitUser() {
      // 提交用户表单
      axios
        .post(baseUrl + "/userlogin/insertuser/", { users: [this.adduserform] })
        .then((res) => {
          console.log(res);
          if (res.status == "200") {
            this.$message({
              type: "success",
              message: "用户添加成功",
            });
          } else {
            this.$message({
              type: "error",
              message: res.msg,
            });
          }
          this.adduserform = "";
          this.adduserdialogVis = false;
          this.getUserList();
        });
    },
    resetUser(formName) {
      // 重置用户表单
      this.$refs[formName].resetFields();
    },
    tableEdit(row, column, cell, event) {
      console.log(row);
      //双击表格某个单元格修改信息
      console.log(row, column, cell, event);
      // 限定修改属性
      let flag = column.property == "userPassword" || column.property == "userFlag"
      if(flag === false) {
        return;
      }

      if (column.property == "userPassword") {
        //置空单元格容器内元素
        event.target.innerHTML = "";
        let preText  = row.userPassword;
        //替换成el-input
        let cellInput = document.createElement("input");
        cellInput.value = "";
        cellInput.setAttribute("type", "text");
        cellInput.style.width = "80%";
        
        cell.appendChild(cellInput);
        
        // 失去焦点后  将input移除
        cellInput.onblur = function () {
          cell.removeChild(cellInput);
          if(cellInput.value === '') {
            cellInput.value = preText;
          }
          event.target.innerHTML = cellInput.value; // 换成原有的显示内容
          // 调用axios接口
          axios
            .post(baseUrl + "/userlogin/updatapassword", {
              userId: row.userId,
              userPassword: cellInput.value,
            })
            .then((res) => {
              console.log(res);
              alert("密码修改成功！");
            });
        };
      }
    },
    handleDelete(row) {
      // 删除选中的用户
      console.log(row);
      let userid = row.userId;
      axios
        .post(baseUrl + "/userlogin/deleteuser/", { userId: userid })
        .then((res) => {
          alert("该用户删除成功！");
          this.getUserList();
        });
    },
    dateFormat(data) {
      // 日期格式化
      return moment(data).format("YYYY-MM-DD HH:mm:ss");
    },
  },
};
</script>

